﻿$import( "SmitearWebGL.Events.EventDispatcher" );
$import( "SmitearWebGL.Events.ResourceEvent" );
$import( "SmitearWebGL.Core.ReferenceCounter" );

SmitearWebGL.Core.ResourceItem = SmitearWebGL.Events.EventDispatcher.extend(
{
	/******** constructor ********/
	
	init : function()
	{
		/******** private property ********/

		this.name = "";
		this.context = null;
		
		this._referenceCount = new SmitearWebGL.Core.ReferenceCounter();
		this._resourceHandle = SmitearWebGL.Core.Math.MAX_NUMBER_VALUE;
		this._resourcePool = null;
		this._resourceFlags = new SmitearWebGL.Core.Math.BitFlags();
		
		this._super();
		this._registClass( "SmitearWebGL.Core.ResourceItem" );
	}
	,
	
	/******** public method ********/
	
	setResourceHandle : function( handle )
	{
		this._resourceHandle = handle;
	}
	,
	setResourcePool : function( pool )
	{
		this._resourcePool = pool;
	}
	,
	getResourceHandle : function()
	{
		return this._resourceHandle;
	}
	,
	getResourcePool : function()
	{
		return this._resourcePool;
	}
	,
	create : function( params )
	{
		$THROW( ! this.isResourceCreated(), "该资源已经创建." );

		this._createResource( params );
		
		this._notifyCreated();
	}
	,
	release : function()
	{
		if ( this.isResourceCreated() )
		{
			var refCount = this._referenceCount.release();
	
			if ( refCount == 0 )
			{
				if ( this._resourcePool )
				{
					this._resourcePool.destroyResource( this._resourceHandle );
					this._destroyResource();
					this._notifyDestroyed();
				}
			}
		}
	
		return refCount;
	}
	,
	isResourceCreated : function()
	{
		return this._resourceFlags.testBit( SmitearWebGL.Core.ResourceItem.nCreated );
	}
	,
	addRef : function()
	{
		return this._referenceCount.addRef();
	}
	,
	getReferenceCount : function()
	{
		return this._referenceCount.getReferenceCount();
	}
	,
	
	/******** private method ********/
	
	_createResource : function( params )
	{
	}
	,
	_destroyResource : function()
	{
	}
	,
	_notifyCreated : function()
	{
		this._resourceFlags.setBit( SmitearWebGL.Core.ResourceItem.nCreated, true );
		this.dispatchEvent( new SmitearWebGL.Events.ResourceEvent( SmitearWebGL.Events.ResourceEvent.CREATED ) );
	}
	,
	_notifyDestroyed : function()
	{
		this._resourceFlags.setBit( SmitearWebGL.Core.ResourceItem.nCreated, false );
		this.dispatchEvent( new SmitearWebGL.Events.ResourceEvent( SmitearWebGL.Events.ResourceEvent.DESTROYED ) );
	}
}
);

/******** static property ********/

SmitearWebGL.Core.ResourceItem.nCreated = 0;
SmitearWebGL.Core.ResourceItem.nLoaded = 1;
SmitearWebGL.Core.ResourceItem.nDisabled = 2;
SmitearWebGL.Core.ResourceItem.nAltered = 3;